package com.engc.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.SimpleTimeZone;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;



/**
 * 时间转换工具类
 * 
 * @author tianfeng
 * 
 */
public abstract class DateUtil {
	private final static Log log = LogFactory.getLog(DateUtil.class);
	public final static int   SECONDS_OF_HOUR  = 3600;
	public final static int   MILLISECONDS_OF_HOUR  = SECONDS_OF_HOUR*1000;
	//一天
	public final static long  MILLISECONDS_OF_DAY  = 24*MILLISECONDS_OF_HOUR;
	public final static int  SECONDS_OF_DAY  = 24*SECONDS_OF_HOUR;
	/**
	 * 格式如下： yyyy-MM-dd HH:mm:ss
	 */
	public final static int DATE_FORMAT_BY_TIME = 1;

	/**
	 * 格式如下： yyyy-MM-dd
	 */
	public final static int DATE_FORMAT_BY_DATE = 2;

	/**
	 * 格式如下： yyyy/MM/dd HH:mm:ss
	 */
	public final static int DATE_FORMAT_BY_OTHER_TIME = 3;
	/**
	 * 格式如下： yyyy/MM/dd
	 */
	public final static int DATE_FORMAT_BY_OTHER_DATE = 4;
	
	/**
	 * 格式如下： yyyyMMddHHmmss
	 */
	public final static int DATE_FORMAT_BY_SIAMPLE_TIME = 5;
	/**
	 * 格式如下： yyyyMMdd
	 */
	public final static int DATE_FORMAT_BY_SIAMPLE_DATE = 6;
	
	public final static int DATE_FORMAT_BY_EASY_DATE = 7;
	
	
	public static SimpleDateFormat getTimeFormat(){ 
		return new SimpleDateFormat(FormatConfig.TIME);
	}
	public static SimpleDateFormat getOtherTimeFormat() {
		return new SimpleDateFormat(FormatConfig.OTHER_TIME);
	}
	public static SimpleDateFormat getOtherDateFormat() {
		return new SimpleDateFormat(FormatConfig.OTHER_DATE);
	}
	public static SimpleDateFormat getDateFormat() {
		return new SimpleDateFormat(FormatConfig.DATE);
	}
	public static SimpleDateFormat getSampleTimeFormat() {
		return new SimpleDateFormat(FormatConfig.SAMPLE_TIME);
	}
	public static SimpleDateFormat getSampleDateFormat() {
		return new SimpleDateFormat(FormatConfig.SAMPLE_DATE);
	}
	public static SimpleDateFormat getHourDateFormat(){
		return new SimpleDateFormat(FormatConfig.HOUR_TIME);
	}
	
	public static SimpleDateFormat getEasyDateFormaty(){
		return new SimpleDateFormat(FormatConfig.EASY_DATE);
	}
	
	
	
	
	private final static SimpleDateFormat rssDate = new SimpleDateFormat(
			"EEE, d MMM yyyy HH:mm:ss z", Locale.US);
	private final static SimpleTimeZone aZone = new SimpleTimeZone(8, "GMT");
	static {
		rssDate.setTimeZone(aZone);
	}

	/**
	 * 将日期对象转换为RSS用的字符串日期
	 * 
	 * @param date
	 * @return
	 */
	public static String dateToRssDate(Date d) {
		return rssDate.format(d);
	}
	
	public static Date getNowMinuteDate() {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.SECOND,0);
		return c.getTime();
	}
	
	public static Date getNowHourDate() {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.SECOND,0);
		c.set(Calendar.MINUTE,0);
		return c.getTime();
	}
	
	public static Date[] getPreDates(int days){
		Date []dates = new Date[days];
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR_OF_DAY,0);
		c.set(Calendar.MINUTE,0);
		c.set(Calendar.SECOND,0);
		dates[0] = c.getTime();
		for(int i=1;i<days;i++){
			c.add(Calendar.DAY_OF_YEAR,-1);
			dates[i] = c.getTime();
		}
		return dates;
	}
	
	
	public static String hourTimeFormat(Date date) {
		return getHourDateFormat().format(date);
	}
	
	public static String[] formats(SimpleDateFormat sdf,Date[] dates){
		String [] dateFormats = new String[dates.length];
		try {
			for(int i=0;i<dates.length;i++){
				dateFormats[i] = sdf.format(dates[i]);
			}
		} catch (Exception e) {
			log.error("formats "+dates[0], e);
		}	
		return dateFormats; 
	}
	
	public static String[] formats(SimpleDateFormat sdf,List<Date> dateList,int size){
		if(dateList==null || dateList.size() >size){
			log.error("formats error");
		}
		String [] dateFormats = new String[size];
		try {
			for(int i=0;i<dateList.size();i++){
				dateFormats[i] = sdf.format(dateList.get(i));
			}
		} catch (Exception e) {
			log.error("formats "+dateList.get(0), e);
		}	
		return dateFormats; 
	}

	/**
	 * 将RSS日期字符串转换为日期对象
	 * 
	 * @param rssDate
	 * @return
	 */
	public static Date rssDateToDate(String rd) {
		boolean ret = false;
		try {
			Date d  = rssDate.parse(rd);
			ret = true;
			return d;
		} catch (Exception e) {
			log.error("rssDateToDate date "+rd,e);
		}finally{
			if(!ret){
				log.error("rssDateToDate date "+rd);
			}
		}
		return null;
	}
	
	
	/**
	 * 将时间对象转换为yyyyMMddHHmmss格式用的字符串时间
	 * 
	 * @param date
	 * @return
	 */
	public static String sampleTimeFormat(Date date) {
		return getSampleTimeFormat().format(date);
	}
	
	/**
	 * 将时间对象转换为yyyyMMdd格式用的字符串时间
	 * 
	 * @param date
	 * @return
	 */
	public static String sampleDateFormat(Date date) {
		return getSampleDateFormat().format(date);
	}


	/**
	 * 将时间对象转换为yyyy/MM/dd HH:mm:ss格式用的字符串时间
	 * 
	 * @param date
	 * @return
	 */
	public static String otherTimeFormat(Date date) {
		return getOtherTimeFormat().format(date);
	}

	/**
	 * 将时间对象转换为yyyy-mm-dd HH:mm:ss格式用的字符串时间
	 * 
	 * @param date
	 * @return
	 */
	public static String timeFormat(Date date) {
		return getTimeFormat().format(date);
	}

	/**
	 * 将日期对象转换为yyyy-mm-dd 格式用的字符串日期
	 * 
	 * @param date
	 * @return
	 */
	public static String dateFormat(Date date) {
		return getDateFormat().format(date);
	}

	/**
	 * 将日期对象转换为yyyy/mm/dd 格式用的字符串日期
	 * 
	 * @param date
	 * @return
	 */
	public static String otherDateFormat(Date date) {
		return getOtherDateFormat().format(date);
	}

	/**
	 * 将格式为yyyy-mm-dd HH:mm:ss字符串时间转换成时间对象
	 * 
	 * @param date
	 * @return
	 */
	public static Date parseTime(String date) {
		boolean ret = false;
		try {
			Date d= getTimeFormat().parse(date);
			ret = true;
			return d;
		} catch (Exception e) {
			log.error("parseTime date "+date,e);
		}finally{
			if(!ret){
				log.error("parseTime date "+date);
			}
		}
		return null;
	}
	
	/**
	 * 将格式为yyyyMMddHHmmss字符串时间转换成时间对象
	 * 
	 * @param date
	 * @return
	 */
	public static Date parseSampleTime(String date) {
		boolean ret = false;
		try {
			Date d= getSampleTimeFormat().parse(date);
			ret = true;
			return d;
		} catch (Exception e) {
			log.error("parseSampleTime date "+date,e);
		}finally{
			if(!ret){
				log.error("parseSampleTime date "+date);
			}
		}
		return null;
	}
	
	/**
	 * 将格式为yyyyMMdd字符串时间转换成时间对象
	 * 
	 * @param date
	 * @return
	 */
	public static Date parseSampleDate(String date) {
		boolean ret = false;
		try {
			Date d= getSampleDateFormat().parse(date);
			ret = true;
			return d;
		} catch (Exception e) {
			log.error("parseSampleDate date "+date,e);
		}finally{
			if(!ret){
				log.error("parseSampleDate date "+date);
			}
		}
		return null;
	}

	/**
	 * 将格式为yyyy/mm/dd HH:mm:ss字符串时间转换成时间对象
	 * 
	 * @param date
	 * @return
	 */
	public static Date parseOtherTime(String date) {
		boolean ret = false;
		try {
			Date d= getOtherTimeFormat().parse(date);
			ret = true;
			return d;
		} catch (ParseException e) {
			log.error("parseOtherTime date "+date,e);
		}finally{
			if(!ret){
				log.error("parseOtherTime date "+date);
			}
		}
		return null;
	}

	/**
	 * 将格式为yyyy-mm-dd字符串日期转换成日期对象
	 * 
	 * @param date
	 * @return
	 */
	public static Date parseDate(String date) {
		boolean ret = false;
		try {
			Date d= getDateFormat().parse(date);
			ret = true;
			return d;
		} catch (Exception e) {
			log.error("parseDate date "+date, e);
		}finally{
			if(!ret){
				log.error("parseDate date "+date);
			}
		}
		return null;
	}
	
	public static Date parseEasyDate(String date){
		boolean ret = false;
		try{
			Date d = getEasyDateFormaty().parse(date);
			ret = true;
			return d;
		}catch(Exception e){
			log.error("parseDate date "+date, e);
		}finally{
			if(!ret){
				log.error("parseDate date "+date);
			}
		}
		return null;
	}
	
	/**
	 * 将格式为yyyy/mm/dd字符串日期转换成日期对象
	 * 
	 * @param date
	 * @return
	 */
	public static Date parseOtherDate(String date) {
		boolean ret = false;
		try {
			Date d = getOtherDateFormat().parse(date);
			return d;
		} catch (ParseException e) {
			log.error("parseOtherDate date "+date, e);
		}finally{
			if(!ret){
				log.error("parseOtherDate date "+date);
			}
		}
		return null;
	}

	/**
	 * 获取当前系统时间yyyy/mm/dd HH:mm:ss格式表示的字符串
	 * 
	 * @return
	 */
	public static String getOtherNowTime() {
		return otherTimeFormat(new Date());
	}

	/**
	 * 获取当前系统时间yyyy-mm-dd HH:mm:ss格式表示的字符串
	 * 
	 * @return
	 */
	public static String getNowTime() {
		return timeFormat(new Date());
	}

	/**
	 * 获取当前系统时期yyyy-mm-dd格式表示的字符串
	 * 
	 * @return
	 */
	public static String getNowDate() {
		return dateFormat(new Date());
	}
	
	
	/**
	 * 获取当前系统时期yyyy-mm-dd格式表示的字符串
	 * 
	 * @return
	 */
	public static Date getDate() {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR_OF_DAY,0);
		c.set(Calendar.MINUTE,0);
		c.set(Calendar.SECOND,0);
		return c.getTime();
	}
	
	public static Date[] getDates() {
		Date [] dates = new Date [2];
		Calendar c = Calendar.getInstance();
		dates[0] = c.getTime();
		c.set(Calendar.HOUR_OF_DAY,0);
		c.set(Calendar.MINUTE,0);
		c.set(Calendar.SECOND,0);
		dates[1] = c.getTime();
		return dates;
	}
	
	
	public static Calendar getCalendar() {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR_OF_DAY,0);
		c.set(Calendar.MINUTE,0);
		c.set(Calendar.SECOND,0);
		return c;
	}
	
	/**
	 * 获取当天上个月的日期
	 * 
	 * @return
	 */
	public static Date preMonthDate() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, -1);
		c.set(Calendar.HOUR_OF_DAY,0);
		c.set(Calendar.MINUTE,0);
		c.set(Calendar.SECOND,0);
		return c.getTime();
	}
	
	public static Date preWeekDate() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_YEAR,-6);
		c.add(Calendar.HOUR_OF_DAY,0);
		c.set(Calendar.MINUTE,0);
		c.set(Calendar.SECOND,0);
		return c.getTime();
	}
	
	
	/**
	 * 获取日期为星期几
	 * @param date
	 * @return 1-星期一 2-星期二 ...7-星期日
	 */
	public static int getWeek(Date date){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int week=c.get(Calendar.DAY_OF_WEEK);
		return week==1?7:(week-1);
	}
	/**
	 * 获取当前星期几
	 * @return 1-星期一 2-星期二 ...7-星期日
	 */
	public static int getWeek(){
		Calendar c = Calendar.getInstance();
		int week=c.get(Calendar.DAY_OF_WEEK);
		return week==1?7:(week-1);
	}
	
	/**
	 * 两个时间相差天数
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	public static int getDiffDays(Date beginDate,Date endDate){
		Calendar begin =  Calendar.getInstance();
		begin.setTime(beginDate);
		begin.set(Calendar.HOUR_OF_DAY,0);
		begin.set(Calendar.MINUTE,0);
		begin.set(Calendar.SECOND,0);
		
		Calendar end =  Calendar.getInstance();
		end.setTime(endDate);
		end.set(Calendar.HOUR_OF_DAY,0);
		end.set(Calendar.MINUTE,0);
		end.set(Calendar.SECOND,0);
		return (int) ((end.getTime().getTime()-begin.getTime().getTime())/MILLISECONDS_OF_DAY);
	}
	/** 
     *   根据日期得到年龄 
     *   @param   birthday   日期类型参数 
     *   @return   返回年龄 
     */ 
   public static  int   getAge(Date   birthday){ 
       int   result=-1; 
       if(birthday!=null){ 
           Date   date   =   new   Date(); 
           int   nowYear   =   date.getYear(); 
           int   nowMonth   =   date.getMonth(); 
           int   nowDate   =   date.getDate(); 
           int   oldYear   =   birthday.getYear(); 
           int   oldMonth   =   birthday.getMonth(); 
           int   oldDate   =   birthday.getDate(); 

           result   =   nowYear   -   oldYear; 
           if   (oldMonth   >   nowMonth)   { 
               result   =   result   -   1; 
           } 
           else 
           if   (oldMonth   ==   nowMonth)   { 
               if   (oldDate   >   nowDate)   { 
                   result   =   result   -   1; 
               } 
           } 
       } 
       return   result; 
   }
   
	/** 
    *   根据日期得到年龄 
    *   @param   birthday   日期类型参数 
    *   @return   返回年龄 
    */ 
   public static  int   getAge(Date birthday,Date jointime){ 
       int   result=-1; 
       if(birthday!=null){ 
           int   nowYear   =   jointime.getYear(); 
           int   nowMonth   =   jointime.getMonth(); 
           int   nowDate   =   jointime.getDate(); 
           int   oldYear   =   birthday.getYear(); 
           int   oldMonth   =   birthday.getMonth(); 
           int   oldDate   =   birthday.getDate(); 

           result   =   nowYear   -   oldYear; 
           if   (oldMonth   >   nowMonth)   { 
               result   =   result   -   1; 
           } 
           else 
           if   (oldMonth   ==   nowMonth)   { 
               if   (oldDate   >   nowDate)   { 
                   result   =   result   -   1; 
               } 
           } 
       } 
       return   result; 
   }
   
   public static Date addYear(int years){
	   Calendar cal = Calendar.getInstance();//使用默认时区和语言环境获得一个日历。    
	   int year =cal.get(Calendar.YEAR);
       cal.set(Calendar.YEAR,year-years);
	   return cal.getTime();
   }
   
   public static void main(String[] args)throws Exception{
	   System.out.println(DateUtil.getAge("2002-12-21","2006-11-21"));
   }
   
   
   /**
    * 21日之前，返回月底时间
    * 21日或其以后,返回下月底时间
    * @return
    */
	public static String getAvailabeDate() {
		SimpleDateFormat datef = new SimpleDateFormat("dd");
		String today = datef.format(new Date());
		datef = new SimpleDateFormat("yyyy-MM-dd");
		Calendar curCal = Calendar.getInstance();
		if (Integer.parseInt(today) >= 20) {
			// 下月底
			curCal.add(Calendar.MONTH, 1);
			curCal.set(Calendar.DATE, 1);
			curCal.roll(Calendar.DATE, -1);
			Date endTime = curCal.getTime();
			return datef.format(endTime);

		} else {
			// 本月末
			curCal.set(Calendar.DATE, 1);
			curCal.roll(Calendar.DATE, -1);
			Date endTime = curCal.getTime();
			return datef.format(endTime);

		}
	}
   
	public static String formatToSS(Date d) {
		return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(d);
	}
	
	
	public static String formatToCron(String time) throws Exception {
		try {
			String[] arr = time.split(":");
			if (arr.length != 3) {
				throw new Exception();
			}

			return "" + Integer.parseInt(arr[2]) + " " + Integer.parseInt(arr[1]) + " " + Integer.parseInt(arr[0]) + " * * ?";
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("时间转化成cron出错...");
			throw e;
		}
	}

	public static String DateToString(Date date) {
		SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
		return sf.format(date);
	}

	public static Date StringToDate(String date) {
		SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
		try {
			return sf.parse(date);
		} catch (ParseException e) {
			System.out.println("日期格式化出错...");
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取结束日期的下一天
	 * 
	 * @param endDate
	 * @return
	 */
	public static Date getEndNextDate(Date endDate) {
		if (endDate != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(endDate);
			cal.add(Calendar.DAY_OF_YEAR, 1);
			Date newenddate = cal.getTime();
			return newenddate;
		} else {
			return null;
		}
	}
	
	/**
	 * 计算入学时年龄
	 * 
	 * @param birthday 出生日期
	 * @param jointime 加入日期
	 * @return
	 */
	public static long getAge(String birthday,String jointime) throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date birthdayDate= sdf.parse(birthday);
		Date jointimeDate= sdf.parse(jointime);
		return getAge(birthdayDate,jointimeDate);
	}
	
	/**
	 * 获取该日期的前几个月
	 * */
	public static Date getBeforDate(Date date,int month){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.MONTH, c.get(Calendar.MONTH)-month);
		return c.getTime();
	}
	
	/**
	 * 获取该日期后的几个月
	 * */
	public static Date getAfterDate(Date date,int month){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.MONTH, c.get(Calendar.MONTH)+month);
		return c.getTime();
	}
	
	
	
	public static String longToDate(Long s){
		Date date = new Date(s);
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
	}
	
	
	public static String getCurTime(){
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
	}
	
	public static String getFullTime(){
		return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
	}
   
	public static String returnformart(String date){
		System.out.println(date);
		SimpleDateFormat sFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String datetimeString="";
		try {
			Date newDate=sFormat.parse(date);
			System.out.println(newDate);
			datetimeString=sFormat.format(newDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
		}
		return  datetimeString;
	}
	
	public static Date returnformatDate(String date) {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		Date sfdate = null;
		try {
			sfdate = sf.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sfdate;
	}
	
	public static Date returnformatDate_import(String date) {
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		Date sfdate = null;
		try {
			sfdate = sf.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sfdate;
	}

	/**
	 * 返回yyyy-MM-dd字符串
	 * 
	 * @return
	 */
	public static String returnformart2(String datetime) {
		Date date = returnformatDate(datetime);
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String dateString = sf.format(date);
		return dateString;
	}
	//当前时间字符串
	public static String returnformartnow() {
		Date date = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String dateString = sf.format(date);
		return dateString;
	}
	
	public static boolean compareDate(String startdate,String enddate) throws Exception{
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		Date startDate = sf.parse(startdate);
		Date endDate = sf.parse(enddate);
		return startDate.before(endDate);
	}
}
